//
//  UserAccount.swift
//  weibo1
//
//  Created by Apple on 15/11/28.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding{
    
    //name	string	友好显示名称
    var name :String?
    //    avatar_large	string	用户头像地址（大图），180×180像素
    var avatar_large :String?
    //    access_token	string	用于调用access_token，接口获取授权后的access token。
    var access_token : String?
    
    //    expires_in	string	access_token的生命周期，单位是秒数。
    
    var expires_in : NSTimeInterval = 0 {
        didSet{
           expires_Date = NSDate(timeIntervalSinceNow: expires_in)
        
        }
    
    }
    //转换为date类型
    var expires_Date : NSDate?
    //    uid	string	当前授权用户的UID
    var uid :String?
    
    init(dict: [String : AnyObject]){
        
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
        //存到沙盒路径
        func saveAcount(){
            let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("acount.plist")
            //归档本地文件
            NSKeyedArchiver.archiveRootObject(self, toFile: path)
//            print(path)
         }
    
    class func loadAcouth() -> UserAccount? {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("acount.plist")
        //解挡本地文件
        if let accouth = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount{
            //判断时间是否过期
            if accouth.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending
            {
                return accouth
            }
            
        }
        //能来到这里说明没有登录
        return nil
    }
    
    
    //重写description属性 显示数据
    override var description: String{
        let keys = ["name","avatar_large","access_token","expires_in","uid","expires_Date"]
        return  dictionaryWithValuesForKeys(keys).description
        
    }
    
    
    //解挡 二进制-对象
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
         expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
         uid = aDecoder.decodeObjectForKey("uid") as? String
    }
    //归档 将对象-二进制
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
        aCoder.encodeObject(uid, forKey: "uid")
        
    }
}
